package com.laughing.httpserver.handler;

import com.laughing.httpserver.entity.MappingClassMethod;
import com.laughing.httpserver.entity.Response;
import com.laughing.httpserver.util.ControllerMappingHolder;
import com.laughing.httpserver.util.SpringContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.Socket;

/**
 * 处理请求与响应
 * @author laughing.sheng <laughing1917@yeah.net/>
 * @date 2018/1/26
 * @see com.laughing.httpserver.handler.RequestHelper
 * @see com.laughing.httpserver.handler.ResponseHelper
 */
@Service
@Slf4j
public class SimpleHttpSocketHandler implements SocketHandler {

    @Autowired
    private ControllerMappingHolder controllerMappingHolder;

    /**
     * 处理到来的socket请求，先解析出request，然后调用controller处理，最后输出响应
     */
    @Override
    public void handle(Socket socket) {
        try {
            HttpServletRequest request = RequestHelper.parse(socket);
            HttpServletResponse response = new Response(socket);
            Object object=doDispatcher(request, response);
            ResponseHelper.postProcess(response,object);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 调用controller方法，写入响应
     */
    @SuppressWarnings("unchecked")
    private Object doDispatcher(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String urI = request.getRequestURI();
        MappingClassMethod controllerClazz = controllerMappingHolder.getMappingClassMethod(urI);
        if (controllerClazz != null) {
            Object object = SpringContext.getBean(controllerClazz.getAClass());
            return controllerClazz.getMethod().invoke(object, request, response);
        } else {
            log.error("No Mapping Handler for {}", urI);
            controllerClazz = controllerMappingHolder.getMappingClassMethod("default");
            Object object = SpringContext.getBean(controllerClazz.getAClass());
            return controllerClazz.getMethod().invoke(object, request, response);
        }
    }

}
